package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.SMSUtils;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired(required = false)
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user){
        //获取手机号
        String phone = user.getPhone();
        //生成4为验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        //调用阿里的工具类去发送短信
//        SMSUtils.sendMessage("黑马旅游网","SMS_205126318",phone,code);
        log.info("=====本次验证码：========"+code);
        //把验证码存储到session中。
//        session.setAttribute("phone",code);//不好控制有效时间
        redisTemplate.opsForValue().set("phone",code,1, TimeUnit.MINUTES);
        //返回信息

        return R.success("发送成功");
    }
    @PostMapping("/login")
    public R<User> login(@RequestBody Map<String, String> param,HttpSession session){
        String phone = param.get("phone");
        String code = param.get("code");
        String codeInsession = (String) redisTemplate.opsForValue().get("phone");

        User user=userService.login(phone,code,codeInsession);
        if(user!=null){
            redisTemplate.delete("phone");
            session.setAttribute("user",user.getId());
        }else {
            return R.error("登入失败！");
        }
        return R.success(user);
    }

    @PostMapping("/loginout")
    public R<String> loginout(HttpSession session){
        session.invalidate();
        return R.success("退出成功！");
    }
}
